package com.konne.nightmare.FastPublicOpinion.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;

import com.yanzhenjie.recyclerview.SwipeRecyclerView;

public class TRecyclerView extends SwipeRecyclerView {

    private View emptyView;

    public TRecyclerView(Context context) {
        super(context);
    }

    public TRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setAdapter(@NonNull Adapter adapter){
        final Adapter<SwipeRecyclerView.ViewHolder> originAdapter = getAdapter();
        if (originAdapter != null){
            originAdapter.unregisterAdapterDataObserver(DataObserver);
        }
        super.setAdapter(adapter);
        adapter.registerAdapterDataObserver(DataObserver);
        judgeEmpty();
    }

    //设置item的下划线
    public void setItemUnderline(ItemDecoration underline){
        super.addItemDecoration(underline);
    }

    public void setLayoutManager(LayoutManager manager){
        super.setLayoutManager(manager);
    }

    public void setEmptyView(View emptyView){
        this.emptyView = emptyView;
        judgeEmpty();
    }
    
    private void judgeEmpty(){
        if (emptyView != null && getAdapter() != null){
            boolean isHasData = getAdapter().getItemCount() != 0;
            emptyView.setVisibility(isHasData ? GONE : VISIBLE);
            super.setVisibility(isHasData ? VISIBLE : GONE);
        }
    }

    private final AdapterDataObserver DataObserver = new AdapterDataObserver() {

        @Override
        public void onChanged() {
            super.onChanged();
            judgeEmpty();
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            super.onItemRangeChanged(positionStart, itemCount);
            judgeEmpty();
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            judgeEmpty();
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            super.onItemRangeRemoved(positionStart, itemCount);
            judgeEmpty();
        }
    };

}
